
//声明构造函数 Promise
function Promise(executor){
    const self = this;
    //状态属性
    self.promiseState = 'pending';
    //结果值属性
    self.promiseResult = null;

    function resolve(value){
        //1. 修改 promise 对象的状态
        self.promiseState = 'fulfilled';
        //2. 设置 promise 成功的结果值
        self.promiseResult = value;
    }

    function reject(reason){
        self.promiseState = 'rejected';
        self.promiseResult = reason;
    }

    try{
        //执行器函数 executor 是同步调用的
        executor(resolve, reject);
    }catch(e){
        reject(e);
    }
}

//声明 Promise.prototype.then 方法
Promise.prototype.then = function(onFulfilled, onRejected){
    //执行成功回调
    if(this.promiseState === 'fulfilled'){
        // 处理成功的结果值
        onFulfilled(this.promiseResult);
    }
    //执行失败回调
    if(this.promiseState === 'rejected'){
        onRejected(this.promiseResult);
    }
}